<?php
class Campaign extends Controller
{
	private  $_template_f;
	private $_numShowItem = 20;
	function __construct()
	{
		parent::Controller();
		$this->_lang = $this->mycommon->getLangCode();
		$this->load->language('common', $this->_lang);
		$common_lang = $this->lang->line('common_lang');
		if(!$this->session->userdata('uname'))
		{
			redirect(site_url('/login'));
			die();
		}
		else
		{
			$permitid = $this->session->userdata('permitid');
			if(!is_numeric($permitid) || $permitid > -1)
			{
				show_error($common_lang['access_denied']);
				die();
			}
		}
		
		$this->_template_f = $this->config->item('template_f');
		$this->load->language('campaign/campaign', $this->_lang);
		$this->load->library('mychart');
        $this->load->model('campaign/campaign_model');	
	}
	
	function _loadHeader($title = '')
	{
		$header = array();
		$header['title'] = $title == '' ? 'Self serving' : $title;
		$header['template_f'] = $this->_template_f;
		
		$header['username'] = '';
		$header['userid'] = '';
		$header['permitid'] = '';
        $header['module_name'] = 'campaign';
		$header['lang'] = $this->_lang;
		$header['common_lang'] = $this->lang->line('common_lang');
		if($this->session->userdata('uname'))
		{
			$header['username'] = $this->session->userdata('uname');
			$header['userid'] = $this->session->userdata('uid');
			$header['permitid'] = $this->session->userdata('permitid');
		}
		
		// load header
		$this->load->view($this->_template_f . 'preheader_view');
		$this->load->view($this->_template_f . 'header_view', $header);
	}
    
	function _loadMenu()
	{
		$data = array();
		$data['username'] = '';
		$data['userid'] = '';
		$data['permitid'] = '';
		$data['lang'] = $this->_lang;
		if($this->session->userdata('uname'))
		{
			$data['username'] = $this->session->userdata('uname');
			$data['userid'] = $this->session->userdata('uid');
			$data['permitid'] = $this->session->userdata('permitid');
		}
		$data['common_lang'] = $this->lang->line('common_lang');
		
		$this->load->view($this->_template_f . 'menu_view', $data);
	}
	
	function _loadFooter()
	{
		$this->load->view($this->_template_f . 'footer_view');
	}
	
    function index()
	{	
		
		$fromDate = $this->input->get('fromdate');
		$fromDate = ($fromDate == '') ? date('Y-m-d', strtotime ( '-7 day' , strtotime (date('Y-m-d')))) : $fromDate;
		
		$todate = $this->input->get('todate');
		$todate = ($todate == '') ? date('Y-m-d') : $todate;
		
		$status = $this->input->get('status');
		$status = $status == '' ? '123' : $status;
		$groupid = $this->input->get('groupid');
		$groupid = is_numeric($groupid) && $groupid != '' ? $groupid : -1;
		$strUserId = $this->input->get('user', true);
		$strContract = $this->input->get('contract', true);
		$cPage = $this->input->get('cpage', true);
		$cPage = is_numeric($cPage) && $cPage != '' ? $cPage : 1;	
		$numShowItem = $this->input->get('numitem', true);
		$numShowItem = is_numeric($numShowItem) && $numShowItem != '' ? $numShowItem : $this->_numShowItem;
				
		$data = array();
		$data['fromdate']= date('d-m-Y', strtotime($fromDate)); 
        $data['todate']= date('d-m-Y', strtotime($todate));
        
        $data['fdateUrl']= $fromDate; 
        $data['tdateUrl']= $todate;
        
        $data['status'] = $status;
        $data['groupid'] = $groupid;
        $data['strUserId'] = $strUserId;
        $data['contract'] = $strContract;
        $data['cPage'] = $cPage;
        $data['numShowItem'] = $numShowItem;
        
        $data['userid'] = $userid = $this->session->userdata('uid');
        $data['permitID'] = $permitID = $this->session->userdata('permitid');
        
        $data['lstUser'] = array();
        if($strUserId != '')
        {
        	$data['lstUser'] = $this->campaign_model->get_user_by_listid($strUserId);
        }
                
        $price = $this->config->item('cpc_price');
        $data['type'] = $type = (is_numeric($this->input->get('type'))&&($this->input->get('type')>0))? $this->input->get('type'):0;
        if(($type!=0)&&($type!=1))
        {
            $data['type'] = $type = 0;
        }
		$allCampaign=$this->campaign_model->getAllCampaign($userid, $status, $fromDate, $todate, $permitID, $price, $strUserId, $cPage, $numShowItem,$groupid,$strContract);
        $data['info'] = $allCampaign['lstCamp'];
        
        $data['pCount'] = $allCampaign['pCount'];
        
        $lstCampaign = $this->campaign_model->selfservingGetListCampaign($userid, $status, $fromDate, $todate, $permitID);
        $data['lstCampaign']=$lstCampaign['lstCam'];
        $data['temp']=array();
        $data['temp']= $this->input->get('lstBanner') ? explode(',',$lstBanner):array();
        
        $data['campaign_lang']=$this->lang->line('campaign_lang');
        
        $data['lstGroup'] = $this->campaign_model->get_all_group();
        $this->_loadHeader('Self Serving - All campaign');
        $this->_loadMenu();
        
        $this->load->view($this->_template_f . 'campaign/campaign_view',$data);

        $this->_loadFooter();
	}
    
    function filter($userid, $states, $fromdate, $todate, $permitID)
    {
        $fromdate = date('Y-m-d',strtotime($fromdate));
        $todate = date('Y-m-d',strtotime($todate));
        $today=date('Y-m-d');
        if($fromdate>$todate)
        {
            echo '<h1>Chưa có dữ liệu,xin chọn ngày khác...</h1>';
        }elseif($fromdate>$today)
        {
            echo '<h1>Chưa có dữ liệu,xin chọn ngày khác...</h1>';
        }else{
            $data['userid']=$userid;
            $data['states']=$states;
            $data['fromdate']=$fromdate;
            $data['todate']=$todate;
            $data['permitID']=$permitID;
            $price = $this->config->item('cpc_price');
            $allCampaign=$this->campaign_model->selfservingGetAllCampaignByUser($userid, $states, $fromdate, $todate, $permitID,$price);
            $data['info']=$allCampaign['info'];
            $data['campaign_lang']=$this->lang->line('campaign_lang');
            $this->load->view($this->_template_f . 'campaign/table_view',$data);
        }
    }
    
    function filter_chart()
    {  
        if(!$this->session->userdata('uname'))
		{
			echo 'unlogin';
			die();
		}
        $todate = $this->input->get('todate');
        if(is_date($todate)==false)
        {
            $data['todate']=$todate=date('Y-m-d');
        }
        $data['fromdate'] = $fromdate = $this->input->get('fromdate');
        if(is_date($fromdate)==false)
        {
            $data['fromdate']=$fromdate = date ( 'Y-m-d' , strtotime ( '-7 day' , strtotime ( $todate ) ) );
        }
        $type = $this->input->get('type');
        if(($type!=0)&&($type!=1))
        {
            $type=0;
        }
        $lstcampaign = $this->input->get('lstcampaign') ? $this->input->get('lstcampaign'):'';
        if($lstcampaign!='')
        {
            $user_id = $this->session->userdata('uid');
            $group_id = $this->session->userdata('groupid');
            $permit_id = $this->session->userdata('permitid');
            $chkCampaign = check_permit_id($user_id,$permit_id,$group_id,$lstcampaign,0);
            if($chkCampaign==false)
            {
                echo 'error';
                die();
            }
        }
        $data = $this->chart_data($fromdate,$todate,$type,$lstcampaign);  
        $this->load->view($this->_template_f . 'campaign/chart_view',$data);        
    }
    function edit()
    {
        $val = $this->input->post('ns') ? $this->input->post('ns'): '123';
        $campaignid=$this->input->get('campaignid');
        $type=$this->input->get('type');
        $userid = $this->session->userdata('uid');
        $count = $this->campaign_model->selfserving_campaign_update_inline($campaignid,$val,$type,$userid);
        if($count==true)
        {
            if($type==1 && $val=='-1'){
                echo '<img src="/images/imgok.gif"/>';
            }elseif($type==1 && $val=='1'){
                echo '<img src="/images/imgrun.gif"/>';
            }elseif($type==1 && $val=='5')
            {
                echo '<img src="/images/imgpause.gif"/>';
            }elseif($type==1 && $val=='2')
            {
                echo '<img src="/images/imgpause.gif"/>';
            }elseif($type==1 && $val=='0')
            {
                echo 'All';
            }elseif(($type==2)||($type==3))
            {
                echo number_format($val);
            }elseif($type==5)
            {
            }else{
                echo $val;
            }
        }else{
            echo 'Error,try again,please!';
        }        
    }
    
    function get_suggest_user()
    {
    	$keyword = trim($this->input->get('keyword', true));
    	$keyword = mb_strtolower($keyword);
		$lstUser = $this->campaign_model->get_suggest_user($keyword);
		$data = array();
		foreach($lstUser as $user)
		{
			$data[] = array('id'=>$user['user_id'], 'name'=>$user['username']);
		}
		echo json_encode($data);
    }
    
    //Export IPs
    function exportIPs()
    {
    	set_time_limit(300);
    	ini_set("memory_limit", "512M");
    	$data = array();
    	
    	$id = (int)$this->input->get('id',true);
    	$fromdate = trim($this->input->get('fromdate',true));
    	$todate = trim($this->input->get('todate',true));
    	if($todate == '' || $fromdate == '')
    	{
    		
    	}
    	else
    	{
    		$fromdate = date('Y-m-d', strtotime($fromdate));
    		$todate = date('Y-m-d', strtotime($todate));
    	}
    	
    	$items = $this->campaign_model->campaignExport_IPs($id, $fromdate, $todate);
    	$data['campaignname'] = $items['name'];
    	$items = $items['items'];
    	$n = count($items);
    	if($n > 0)
    	{
	    	$dateTmp = $items[0]->dt;
	    	$itemsTmp = array();
	    	$ips = array();
	    	foreach($items as $i=>$item)
	    	{
	    		if($item->dt != $dateTmp)
	    		{
	    			$itemsTmp[$dateTmp] = $ips;
	    			$dateTmp = $item->dt;
	    			$ips = array();
	    		}
	    		
	    		$ips[] = $item->ip;
	    	}
	    	$itemsTmp[$dateTmp] = $ips;
	    	
	    	$items = $itemsTmp;
	    	unset($itemsTmp);
    	}
    	else $items = array();
    	
    	$data['items'] = $items;
    	$data['fromdate'] = $fromdate;
    	$data['todate'] = $todate;
    	$data['lang'] = $this->lang->line('campaign_lang');
        $html = $this->load->view($this->_template_f . 'campaign/campaign_export_ips',$data, true);
        $this->load->library('pdfreport');
        $this->load->library('myvietstring');
        $pdf_name = 'admarket_ips_'.str_replace(' ', '_',$this->myvietstring->removeVietChars(strip_tags($data['campaignname']))).'_'.date('d.m.Y').'.pdf';
        $this->pdfreport->html2pdf($html,$pdf_name);
    }
    //end
    function createDataHour($fromdate,$data,$arrBannerid=array()){
		$fromTime=mktime(0,0,0,substr($fromdate,5,2),substr($fromdate,8,2),substr($fromdate,0,4));
		$hour=((time()-$fromTime)>=86400)?24:date('H',time());
		$arrayHour=range(0,$hour-1,1);
		if(empty($arrBannerid)){
			$arrData1=array_fill(0,count($arrayHour),0);		
			foreach($data as $cd){
				$key=(int)str_replace('h','',$cd['hour']);
				$arrData1[$key]=(int)$cd[1];
			}
			$arrData=array('hour'=>$arrayHour,'data'=>$arrData1);
		}
		else{
			$arrData1=array_fill(0,count($arrayHour),0);
			$arrData2=array_fill(0,count($arrayHour),0);		
			foreach($data as $cd){
				$key=(int)str_replace('h','',$cd['hour']);
				if($cd[0]==$arrBannerid[0]){
					$arrData1[$key]=(int)$cd[1];	
				}
				else{
					$arrData2[$key]=(int)$cd[1];	
				}
			}
			$arrData=array('hour'=>$arrayHour,'data1'=>$arrData1,'data2'=>$arrData2);
		}
		return $arrData;
	}
    function createData($arrDate,$fromdate,$data,$arrBannerid=array()){
		$fromTime=mktime(0,0,0,substr($fromdate,5,2),substr($fromdate,8,2),substr($fromdate,0,4));
		if(empty($arrBannerid)){
			$arrData=array_fill(0,count($arrDate),0);		
			foreach($data as $cd){
				$key=ceil((strtotime($cd[0])-$fromTime)/86400);
				$arrData[$key]=(int)$cd[2];
			}
		}
		else{
			$arrData1=array_fill(0,count($arrDate),0);
			$arrData2=array_fill(0,count($arrDate),0);		
			foreach($data as $cd){
				$key=ceil((strtotime($cd[0])-$fromTime)/86400);
				$arrData2[$key]=(int)$cd[2];	
			}
			$arrData=array('data1'=>$arrData1,'data2'=>$arrData2);
		}
        $nowhour = date("H");
		if((int)$nowhour<6){
			$val = count($arrData)-1;
			unset($arrData[$val]);
		}
		return $arrData;
	}
    function chart_data($fromdate,$todate,$type,$lstcampaign)
    {
        $data=array();
        $arrDate=$this->mychart->createDateRangeArray($fromdate,$todate);
        $campaign_lang = $this->lang->line('campaign_lang');
        $userid = $this->session->userdata('uid');
        $permitid = $this->session->userdata('permitid');
        $ok=true;
        $chkLstCampaign=explode(',',$lstcampaign);
        if(count($chkLstCampaign)==2)
        {
            $ok =(($chkLstCampaign[0]>0)&& is_numeric($chkLstCampaign[0])) ? true : false ;  
            $ok =(($chkLstCampaign[1]>0)&& is_numeric($chkLstCampaign[1])) ? true : false ;
        }elseif(count($chkLstCampaign)==1){
            $ok =(($chkLstCampaign[0]>0)&& is_numeric($chkLstCampaign[0])) ? true : false ; 
        }
        
        $lstcampaign = ($ok ==false) ? '': $lstcampaign;
        if($todate==$fromdate)
        {
            $curdate=$fromdate;
            if($lstcampaign=='')
            {
                $chartdata = $this->campaign_model->selfserving_get_campaign_chart_hour($lstcampaign,$curdate,$type,$userid);
                $arrData=$this->mychart->createDataHour($curdate,$chartdata['campaigninfo']);
                $data['type']= ($type==0)? 'Click':$campaign_lang['impressions'];
                $data['data']=json_encode(array('name'=>$campaign_lang['all_campaign'],'data'=>$arrData['data'],'color'=>'#627AAD'));
                $data['date']=json_encode($arrData['hour']);
            }else{
                $data['temp']=$temp=explode(',',$lstcampaign);
                $countLstCampaign= count($temp);
                if($countLstCampaign==1)
                {
                    $chartdata = $this->campaign_model->selfserving_get_campaign_chart_hour($lstcampaign,$curdate,$type,$userid);
                    $arrData=$this->mychart->createDataHour($curdate,$chartdata['campaigninfo']); 
                    $data['type']= ($type==0)? 'Clicks':$campaign_lang['impressions'];
                    $label1=$chartdata['campaignname'][0]['campaignname'];
                    $data['data']=json_encode(array('name'=>strip_tags($label1),'data'=>$arrData['data'],'color'=>'#627AAD'));
                    $data['date']=json_encode($arrData['hour']);
                }else{
                    $chartdata = $this->campaign_model->selfserving_get_campaign_chart_hour($lstcampaign,$curdate,$type,$userid);
                    $arrData=$this->mychart->createDataHour($curdate,$chartdata['campaigninfo'],$temp);
                    if($chartdata['campaignname'][0]['campaignid']==$countLstCampaign[0])
                    {
                        $label1=$chartdata['campaignname'][0]['campaignname'];
                        $label2=$chartdata['campaignname'][1]['campaignname'];
                    }else{
                        $label1=$chartdata['campaignname'][1]['campaignname'];
                        $label2=$chartdata['campaignname'][0]['campaignname'];
                    }
                    $data['type']= ($type==0)? 'Clicks':$campaign_lang['impressions'];
                    $data['data']=json_encode(array('name'=>strip_tags($label1),'data'=>$arrData['data1'],'color'=>'#627AAD'));
                    $data['data1']=json_encode(array('name'=>strip_tags($label2),'data'=>$arrData['data2'],'color'=>'#FF9900'));
                    $data['date']=json_encode($arrData['hour']);
                }
            }
        }else{
            if($lstcampaign=='')
            {
                $chartdata = $this->campaign_model->get_allcampaign_chart($userid,$fromdate,$todate,$permitid,$lstcampaign,$type);
                $arrData=$this->createData($arrDate,$fromdate,$chartdata['campaigninfo']);
                $data['data']=json_encode(array('name'=>$campaign_lang['all_campaign'],'data'=>$arrData,'color'=>'#627AAD'));
                $data['date']=json_encode($arrDate);
                $data['type']= $type==0 ? 'Click' :$campaign_lang['impressions'];
                $data['step'] =(count($arrDate)<=10)?1:((count($arrDate)<=14)?2:floor(count($arrDate)/7));
            }else{
                $data['temp']=$temp=explode(',',$lstcampaign);
                $countLstCampaign= count($temp);
                if($countLstCampaign==1)
                {
                    $chartdata = $this->campaign_model->get_allcampaign_chart($userid,$fromdate,$todate,$permitid,$lstcampaign,$type);
                    $arrData=$this->mychart->createData($arrDate,$fromdate,$chartdata['campaigninfo']);
                    $label1=$chartdata['campaignname'][0]['campaignname'];
                    $data['type'] = ($type==0)? 'Click':$campaign_lang['impressions'] ;
                    $data['data']=json_encode(array('name'=>strip_tags($label1),'data'=>$arrData,'color'=>'#627AAD'));
                    $data['date']=json_encode($arrDate);
                    $data['step'] =(count($arrDate)<=10)?1:((count($arrDate)<=14)?2:floor(count($arrDate)/7));
                }else{
                    $chartdata = $this->campaign_model->get_allcampaign_chart($userid,$fromdate,$todate,$permitid,$lstcampaign,$type);
                    $arrData=$this->mychart->createData($arrDate,$fromdate,$chartdata['campaigninfo'],$temp);
                    if($chartdata['campaignname'][0]['campaignid']==$countLstCampaign[0])
                    {
                        $label1=$chartdata['campaignname'][0]['campaignname'];
                        $label2=$chartdata['campaignname'][1]['campaignname'];
                    }else{
                        $label1=$chartdata['campaignname'][1]['campaignname'];
                        $label2=$chartdata['campaignname'][0]['campaignname'];
                    }
                    $data['type'] = ($type==0)? 'Click':$campaign_lang['impressions'];
                    $data['data']=json_encode(array('name'=>strip_tags($label1),'data'=>$arrData['data1'],'color'=>'#627AAD'));
                    $data['data1']=json_encode(array('name'=>strip_tags($label2),'data'=>$arrData['data2'],'color'=>'#FF9900'));
                    $data['date']=json_encode($arrDate);
                    $data['step'] =(count($arrDate)<=10)?1:((count($arrDate)<=14)?2:floor(count($arrDate)/7));
                }
            }
        }
        return $data;
    }
}
?>